package site.teamo.biu.net.common.util;

import cn.hutool.cache.Cache;
import cn.hutool.cache.CacheUtil;
import cn.hutool.core.lang.PatternPool;
import org.xbill.DNS.*;

import java.net.UnknownHostException;
import java.time.Duration;
import java.util.regex.Matcher;

/**
 * @author haocongshun
 * @date 2023/03/31 16:44:08
 */
public class Domain2IpSearcher {

    private final Resolver resolver;

    private final Cache<String, String> cache;

    private Domain2IpSearcher(String[] servers) throws UnknownHostException {
        this.resolver = new ExtendedResolver(servers);
        this.resolver.setPort(53);
        this.resolver.setTimeout(Duration.ofSeconds(1));
        cache = CacheUtil.newTimedCache(60000L);
    }

    public static Domain2IpSearcher create(String[] servers) throws UnknownHostException {
        if (servers == null || servers.length == 0) {
            throw new RuntimeException("未指定dns服务器");
        }
        return new Domain2IpSearcher(servers);
    }

    public String search(String domain) throws TextParseException {
        if (cache.containsKey(domain)) {
            return cache.get(domain, false);
        }
        //如果传入的就是一个ip则直接返回
        final Matcher matcher = PatternPool.IPV4.matcher(domain);
        if (matcher.matches()) {
            return domain;
        }
        Lookup lookup = new Lookup(domain, Type.A);
        lookup.setResolver(resolver);
        lookup.run();
        if (lookup.getResult() == Lookup.SUCCESSFUL) {
            String ip = lookup.getAnswers()[0].rdataToString();
            cache.put(domain, ip);
            return ip;
        }
        return null;
    }
}
